﻿using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace OpenPasteSpider
{
    /// <summary>
    /// 这里的权限筛选器
    /// </summary>
    public class RoleAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 权限
        /// </summary>
        private string _role { set; get; }

        /// <summary>
        /// 角色
        /// </summary>
        private string _model { get; set; }


        ///// <summary>
        ///// 
        ///// </summary>
        //private readonly ModelCacheHelper _serviceProvider;

        private readonly SpiderConfig _config;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="config"></param>
        /// <param name="model"></param>
        /// <param name="role"></param>
        public RoleAttribute(
            IOptions<SpiderConfig> config,
            string model = "",
            string role = "")
        {
            _model = model;
            _role = role;
            _config = config.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="Volo.Abp.UserFriendlyException"></exception>
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            var needauth = true;
            foreach (var item in context.Filters)
            {
                if (item is RoleAttribute)
                {
                    needauth = (item == this);
                }
            }

            if (needauth)
            {
                if (_model != "any" && _role != "any")
                {
                    if (!context.HttpContext.Request.Headers.ContainsKey("token"))
                    {
                        throw new PasteException("当前未登录，请登录后重试", 401);
                    }
                    var token = context.HttpContext.Request.Headers["token"].ToString();
                    //密钥加密的额校验
                    if (token.CheckToken(_config.UserToken))
                    {
                    }
                    else
                    {
                        throw new PasteException("当前登陆密钥不可用，请重新登陆", 401);
                    }
                }
            }
            base.OnActionExecuting(context);
        }
    }


    /// <summary>
    /// 自定义全局错误处理，使用错误代码httpstatuscode
    /// </summary>
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {

        private readonly ILogger<CustomExceptionFilterAttribute> _logger;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {

            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                var userExpect = (context.Exception.InnerException != null ? context.Exception.InnerException : context.Exception) as Volo.Abp.UserFriendlyException;
                var info = new ErrorInfoModel();
                //info.error = new ErrorInfoModel();
                info.code = "500";
                info.success = false;
                info.message = "服务器遇到一个错误，无法继续为您服务!";

                if (userExpect != null)
                {
                    if (!String.IsNullOrEmpty(userExpect.Code))
                    {
                        info.code = userExpect.Code;
                    }
                    else
                    {
                        info.code = "502";
                    }
                    info.message = context.Exception.Message;
                }
                else
                {
                    var volexception = context.Exception as PasteException;
                    if (volexception != null)
                    {
                        info.code = volexception.Code.ToString();
                        info.message = volexception.Message;
                    }
                    else
                    {
                        var exception = context.Exception.InnerException != null ? context.Exception.InnerException : context.Exception;
                        if (exception != null)
                        {
                            info.code = "500";
                            info.message = exception.Message;
                        }

                    }
                }

                if (context.ModelState != null)
                {
                    if (context.ModelState.Count > 0)
                    {
                        foreach (var key in context.ModelState.Keys)
                        {
                            context.ModelState.TryGetValue(key, out var val);
                            if (val.Errors.Count > 0)
                            {
                                info.message = key + "::" + val.Errors[0].ErrorMessage;
                                info.code = "400";
                                break;
                            }
                        }
                    }
                }

                if (!String.IsNullOrEmpty(info.code) && info.code == "500")
                {
                    //写入日志
                    _logger.LogError(context.Exception, context.HttpContext.Request.Path, null);
                }

                context.Result = new ContentResult
                {
                    // 返回状态码设置为200，表示成功
                    StatusCode = int.Parse(info.code),
                    // 设置返回格式
                    ContentType = "application/json;charset=utf-8",
                    Content = Newtonsoft.Json.JsonConvert.SerializeObject(info)
                };
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override System.Threading.Tasks.Task OnExceptionAsync(ExceptionContext context)
        {
            return base.OnExceptionAsync(context);
        }
    }

}
